# -*- coding: utf-8 -*-
try:
    import dbus
    # import python dbus GLib mainloop support
    import dbus.mainloop.glib

except ImportError :
    print "Install Python-DBUS"
    exit(1) 
    
class Notifier:
    '''
    Constructor
    '''
    def __init__(self, timer= 9, debug = 0, action = None):
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
        bus = dbus.SessionBus()
        notify_obj = bus.get_object("org.kde.plasma-desktop", "/org/freedesktop/Notifications")
        self.notify = dbus.Interface(notify_obj, "org.freedesktop.Notifications")
        self.icon = "kmail"
        self.appname = "Twitter-Daemon"
        self.button = ["1","Open"]
        self.debug = debug
        self.timer = timer
        if (not action): 
            action = self.noop
        action(0,0)
        bus.add_signal_receiver(action, "ActionInvoked", "org.freedesktop.Notifications", "org.kde.plasma-desktop", "/org/freedesktop/Notifications")

    
    def noop(self, twit_id, action_key):
        if self.debug: print "noopa: id=" + twit_id + " action_number =" + action_key
         
    '''
    Text preparation routine
    msg: the text to be prepaired
    '''
    def text_format(self,msg):
        m = msg.split(" ") # Split the message into parts
        msg=[]
        for part in m:
            if part[0:4] == "http" : part = "<a href=\"" + part + "\">" + part + "</a>"
            else : part=part.replace("&","&amp;")
            msg.append(part)
        return " ".join(msg)

    '''
    routine to send the message
    '''
    def send(self,title,text):
        if(self.debug):
            print "Notifier:send:38 " + title
        return self.notify.Notify(self.appname, 0, self.icon, title , self.text_format(text) , self.button, {}, self.timer*1000)


      
